package com.training.net;

import android.content.Intent;

import com.base.MainApplication;
import com.training.activity.LoginActivity;
import com.training.bean.User;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class NetInterceptor implements Interceptor {
    private Set<String> excludedPaths;

    public NetInterceptor() {
        this.excludedPaths = new HashSet<>();
        // 添加不需要token的接口路径
        excludedPaths.add("/api/login");
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request originalRequest = chain.request();
        Request.Builder requestBuilder = originalRequest.newBuilder()
                .header("Content-Type", "application/json");

        // 检查是否在白名单中
        String requestPath = originalRequest.url().encodedPath();
        if (!excludedPaths.contains(requestPath)) {
            User user = DataCenter.instance().getUser();
            if (user != null) {
                requestBuilder.header("Authorization", "Bearer " + user.token);
            }
//            requestBuilder.header("deviceId", MainApplication.instance().deviceId);
        }

        Request newRequest = requestBuilder.build();
        Response response = chain.proceed(newRequest);

        // 检查响应码是否为401（未授权），如果是则跳转到登录页面
        if (response.code() == 401) {
            // 确保MainApplication实例不为空，并且其Handler也不为空
            MainApplication appInstance = MainApplication.instance();
            if (appInstance != null && appInstance.getMainHandler() != null) {
                // 在主线程中执行UI操作
                appInstance.getMainHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        // 清除用户信息
                        DataCenter.instance().clearUserInfo();

                        // 发送广播或事件通知所有Activity跳转到登录页面
                        Intent intent = new Intent(appInstance, LoginActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        appInstance.startActivity(intent);
                    }
                });
            }
        }

        return response;
    }
}